<template>
	<view v-if="aiStore.showDialog" class="ai-dialog-mask">
			<!-- 新增：历史记录抽屉 -->
			<view class="history-drawer" :class="{ 'show': drawerVisible }">
				<view class="drawer-header">
					<text>历史会话</text>
					<button class="close-drawer-btn" @click="toggleHistoryDrawer">
						<image src="/static/icon/AI/close.png" mode="aspectFit" class="close-icon" />
					</button>
				</view>
				<scroll-view scroll-y class="history-list">
					<!-- 修改：字段名从下划线改为驼峰命名 -->
					<view v-for="(record, idx) in historyRecords" :key="idx" class="history-item"
						@click="loadHistory(record.sessionId)">
						<text class="session-id">{{ record.sessionId }}</text>
						<text class="last-input">{{ record.userInput }}</text>
						<text class="time">{{ formatTime(new Date(record.updateTime).getTime()) }}</text>
					</view>
				</scroll-view>
			</view>

		<view class="ai-chat-container">
			<!-- 顶部标题栏（新增历史按钮） -->
			<view class="chat-header">
				<!-- 历史记录按钮 -->
				<button class="history-btn" @click="toggleHistoryDrawer">
					<image src="/static/icon/AI/history.png" mode="aspectFit" class="history-icon" />
				</button>

				<view class="header-left">
					<image src="/static/icon/AI/ai.png" mode="aspectFit" class="header-avatar" />
					<text class="header-title">AI智能助手</text>
				</view>

				<button class="close-btn" @click="aiStore.toggleDialog(false)">
					<image src="/static/icon/AI/close.png" mode="aspectFit" class="close-icon" />
				</button>
			</view>

			<!-- 聊天内容区域 -->
			<scroll-view scroll-y class="chat-history" :scroll-into-view="scrollIntoView" :scroll-with-animation="true">
				<!-- AI消息（左侧：头像 + 对话框） -->
				<view v-for="(msg, idx) in messages" :key="idx" :id="'msg-' + idx" class="message-row"
					:class="msg.role === 'user' ? 'user-row' : 'ai-row'">
					<!-- AI消息 -->
					<template v-if="msg.role === 'ai'">
						<image src="/static/icon/AI/ai.png" mode="aspectFit" class="avatar ai-avatar" />
						<view class="message-bubble ai-bubble">
							<view class="message-content" v-html="msg.content"></view>
							<view class="message-time">{{ formatTime(msg.timestamp) }}</view>
						</view>
						<view class="empty-space"></view>
					</template>

					<!-- 用户消息 -->
					<template v-if="msg.role === 'user'">
						<view class="empty-space"></view>
						<view class="message-bubble user-bubble">
							<view class="message-content" v-html="msg.content"></view>
							<view class="message-time">{{ formatTime(msg.timestamp) }}</view>
						</view>
						<image :src="userInfo.avatar || '/static/icon/user-default.png'" mode="aspectFit"
							class="avatar user-avatar" />
					</template>
				</view>
			</scroll-view>

			<!-- 底部输入区域 -->
			<view class="input-area">
				<view class="input-bar">
					<button class="upload-btn" @click="handleUpload">
						<image src="/static/icon/AI/photo.png" mode="aspectFit" class="upload-icon" />
					</button>

					<input v-model="userInput" class="chat-input" placeholder="请输入你的问题..." :disabled="loading"
						@confirm="onSend" confirm-type="send" />

					<button class="send-btn" @click="onSend" :disabled="loading || !userInput"
						:class="{ disabled: loading || !userInput }">
						<text v-if="!loading">发送</text>
						<view v-else class="loading-indicator">
							<view class="loading-dot"></view>
							<view class="loading-dot"></view>
							<view class="loading-dot"></view>
						</view>
					</button>
				</view>

				<view class="status-area">
					<view v-if="loading" class="loading-hint">
						<text>AI思考中...</text>
					</view>
					<view v-if="errorMsg" class="error-message">
						<text>{{ errorMsg }}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
	import { ref, nextTick, onMounted } from 'vue'
	import { useAiChatStore } from '@/store/aiChatStore' // 引入store
	import { getHistory, getMessage, saveMessageToRedis } from '../../apis/AIChatAPI';

	// 类型定义
	interface Message {
		role : 'user' | 'ai';
		content : string;
		timestamp : number;
	}

	// 获取store实例（核心：通过store管理状态）
	const aiStore = useAiChatStore()

	// 本地状态管理
	const showDialog = ref(true)
	const messages = ref<Message[]>([])
	const sessionId = ref('')
	const userInfo = ref(uni.getStorageSync('userInfo') || {})

	// 本地状态
	const userInput = ref('')
	const loading = ref(false)
	const errorMsg = ref('')
	const scrollIntoView = ref('')
	const messageId = ref('')
	const request = ref({
		sessionId: '',
		messageId: '',
		userId: userInfo.value.userId || '',
		userInput: '',
		aiResponse: ''
	})
	const filePath = ref('')

	// 组件挂载时初始化
	onMounted(() => {
		// 初始化会话ID
		if (!sessionId.value) {
			const timestamp = Date.now().toString(36)
			const randomStr = Math.random().toString(36).substr(2, 9)
			sessionId.value = "mini" + timestamp + randomStr
		}
		request.value.sessionId = sessionId.value
	})

	// 切换对话框显示状态
	const toggleDialog = (visible : boolean) => {
		showDialog.value = visible
	}

	// 发送消息
	const onSend = async () => {
		if (!userInput.value.trim() || loading.value) return

		let input = userInput.value.trim();
		const hasImage = !!filePath.value

		// 拼接图片内容
		if (hasImage) {
			input = `${input}\n[图片filePath]${filePath.value}`
		}

		// 添加用户消息
		const userMessage : Message = {
			role: 'user',
			content: input,
			timestamp: Date.now()
		}
		messages.value.push(userMessage)

		userInput.value = ''
		filePath.value = ''
		loading.value = true
		errorMsg.value = ''

		await nextTick()
		scrollToBottom()

		// 添加AI消息占位
		const aiMessage : Message = {
			role: 'ai',
			content: '',
			timestamp: Date.now()
		}
		messages.value.push(aiMessage)
		await nextTick()
		scrollToBottom()

		// 流式请求
		await streamAIResponse(input, aiMessage)
	}

	// 流式获取AI回复
	function streamAIResponse(input : string, aiMessage : Message) {
		let finished = false
		let lastLength = 0
		request.value.userInput = input
		request.value.sessionId = sessionId.value

		const poll = async () => {
			if (finished) return
			try {
				await new Promise<void>((resolve) => {
					uni.request({
						url: 'http://localhost:1010/ai/chat/stream',
						method: 'POST',
						data: request.value,
						header: { Accept: 'text/event-stream' },
						timeout: 60000,
						success: (res) => {
							const raw = res.data as string
							const lines = raw.split(/\r?\n/).filter(l => l.startsWith('data:'))
							let newText = ''

							for (let i = lastLength; i < lines.length; i++) {
								const chunk = lines[i].replace(/^data:/, '').trim()
								if (chunk === '[END]') {
									finished = true
									break
								}
								newText += chunk
							}

							if (newText) {
								// 更新AI消息内容
								aiMessage.content += newText
								messages.value = [...messages.value]

								lastLength = lines.length
								nextTick(scrollToBottom)
							}

							if (finished || !newText) {
								finished = true
								loading.value = false
								saveChatRecord(input, aiMessage.content)
								resolve()
							} else {
								setTimeout(poll, 600)
								resolve()
							}
						},
						fail: () => {
							errorMsg.value = 'AI请求失败'
							loading.value = false
							finished = true
							resolve()
						}
					})
				})
			} catch {
				loading.value = false
				finished = true
			}
		}
		poll()
	}

	// 保存对话记录
	function saveChatRecord(user : string, ai : string) {
		const timestamp = Date.now().toString(36)
		const randomStr = Math.random().toString(36).substr(2, 9)
		messageId.value = "mini" + timestamp + randomStr
		console.log("MsgId", messageId.value)
		console.log("sessionId", sessionId.value)
		request.value.messageId = messageId.value
		request.value.userInput = user
		request.value.aiResponse = ai
		request.value.sessionId = sessionId.value

		saveMessageToRedis(request.value)
	}

	// 上传文件
	const handleUpload = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ['compressed'],
			sourceType: ['album', 'camera'],
			success: (res) => {
				const tempFilePaths = res.tempFilePaths
				if (!tempFilePaths.length) {
					errorMsg.value = '未选择文件'
					return
				}

				uni.uploadFile({
					url: 'http://localhost:10000/oss/upload',
					filePath: tempFilePaths[0],
					name: 'file',
					success: (uploadRes) => {
						try {
							const result = JSON.parse(uploadRes.data)
							if (result.code === 200) {
								const imageUrl = result.data.url
								filePath.value = imageUrl

								// 添加图片消息
								const imageMessage : Message = {
									role: 'user',
									content: `<img src="${imageUrl}" style="max-width: 100%; border-radius: 8rpx;" />`,
									timestamp: Date.now()
								}
								messages.value.push(imageMessage)
								nextTick(scrollToBottom)
							} else {
								errorMsg.value = `服务器错误: ${result.msg || uploadRes.statusCode}`
							}
						} catch (e) {
							errorMsg.value = '解析响应失败'
						}
					},
					fail: (err) => {
						errorMsg.value = `上传失败: ${err.errMsg}`
					}
				})
			},
			fail: (err) => {
				errorMsg.value = `选择图片失败: ${err.errMsg}`
			}
		})
	}

	// 滚动到底部
	function scrollToBottom() {
		scrollIntoView.value = 'msg-' + (messages.value.length - 1)
	}

	// 格式化时间
	const formatTime = (timestamp : number) => {
		const date = new Date(timestamp)
		const hours = date.getHours().toString().padStart(2, '0')
		const minutes = date.getMinutes().toString().padStart(2, '0')
		return `${hours}:${minutes}`
	}
	// 新增：抽屉显隐控制 + 历史记录数据
	const drawerVisible = ref(false) // 抽屉是否显示
	const historyRecords = ref([])  // 历史会话列表
	
	// 新增：切换抽屉显隐（打开时自动请求历史记录）
	const toggleHistoryDrawer = () => {
	  drawerVisible.value = !drawerVisible.value
	  if (drawerVisible.value) {
	    fetchHistoryRecords() // 打开抽屉时拉取历史记录
	  }
	}
	
	// 新增：请求历史会话列表（需后端接口支持）
	const fetchHistoryRecords = async () => {
	  try {
	    const userId=userInfo.value.userId // 传用户ID筛选会话
		getHistory(userId).then((res:any)=>{
			if (res.data.code === 200) {
				console.log("res",res.data)
			  historyRecords.value = res.data.data // 假设后端返回结构与示例一致
			} else {
			  errorMsg.value = '获取历史记录失败'
			}
		})
	  } catch (e) {
	    errorMsg.value = '网络错误'
	  }
	}
	
	// 新增：加载指定会话的历史消息（需后端接口支持）
	// 加载指定会话的历史消息
	const loadHistory = async (targetSessionId: string) => {
	  try {
	    // 显示加载状态
	    loading.value = true;
	    errorMsg.value = '';
	
	    // 调用接口获取该会话的历史消息
	    const res: any = await getMessage(targetSessionId);
	    
	    if (res.data.code === 200) {
	      // 清空当前消息列表，准备加载历史消息
	      messages.value = [];
	      
	      // 转换后端返回数据为本地Message类型（关键步骤）
	      const historyMessages: Message[] = res.data.data.map((item: any) => ({
	        role: item.role as 'user' | 'ai', // 直接使用后端返回的role
	        content: item.content, // 内容直接复用
	        timestamp: new Date(item.createdAt).getTime() // 转换为时间戳
	      }));
	      
	      // 赋值到消息列表（触发视图更新）
	      messages.value = historyMessages;
	      
	      // 更新当前会话ID，确保后续消息属于该会话
	      sessionId.value = targetSessionId;
	      request.value.sessionId = targetSessionId;
	      
	      // 关闭抽屉
	      toggleHistoryDrawer();
	      
	      // 等待DOM更新后滚动到最底部
	      await nextTick();
	      scrollToBottom();
	    } else {
	      errorMsg.value = res.data.msg || '获取历史消息失败';
	    }
	  } catch (err: any) {
	    errorMsg.value = '加载历史消息出错：' + (err.message || '网络异常');
	  } finally {
	    // 无论成功失败都关闭加载状态
	    loading.value = false;
	  }
	};
</script>

<style lang="scss" scoped>
	/* 历史抽屉容器 */
	.history-drawer {
		position: fixed;
		top: 0;
		left: 0;
		width: 60%;
		max-width: 400rpx;
		height: 100vh;
		background-color: #fff;
		box-shadow: 2rpx 0 10rpx rgba(0, 0, 0, 0.1);
		transform: translateX(-100%);
		/* 初始隐藏 */
		transition: transform 0.3s ease;
		/* 抽屉动画 */
		z-index: 10000;
		/* 层级高于遮罩 */
		padding: 20rpx;
		box-sizing: border-box;
	}

	/* 抽屉显示状态 */
	.history-drawer.show {
		transform: translateX(0);
	}

	/* 抽屉头部 */
	.drawer-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 20rpx 0;
		border-bottom: 1rpx solid #f0f0f0;
	}

	/* 历史记录列表 */
	.history-list {
		flex: 1;
		padding: 20rpx 0;
	}

	/* 单条历史记录项 */
	.history-item {
		padding: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.session-id {
		font-size: 24rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: block;
	}

	.last-input {
		font-size: 28rpx;
		color: #666;
		margin-bottom: 8rpx;
		display: block;
	}

	.time {
		font-size: 22rpx;
		color: #999;
	}

	/* 历史按钮样式 */
	.history-btn {
		width: 52rpx;
		height: 52rpx;
		padding: 0;
		margin-right: 16rpx;
		background-color: transparent;
		border: none;
	}

	.history-icon {
		width: 36rpx;
		height: 36rpx;
	}

	/* 抽屉关闭按钮 */
	.close-drawer-btn {
		width: 48rpx;
		height: 48rpx;
		padding: 0;
		background-color: transparent;
		border: none;
	}

	/* 遮罩层 */
	.ai-dialog-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.6);
		z-index: 9999;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx;
	}

	/* 聊天容器 */
	.ai-chat-container {
		width: 100%;
		max-width: 750rpx;
		height: 85vh;
		background-color: #ffffff;
		border-radius: 24rpx;
		overflow: hidden;
		box-shadow: 0 10rpx 50rpx rgba(0, 0, 0, 0.15);
		display: flex;
		flex-direction: column;
	}

	/* 头部样式 */
	.chat-header {
		padding: 24rpx 30rpx;
		background: linear-gradient(135deg, #1e88e5, #1565c0);
		color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;

		.header-left {
			display: flex;
			align-items: center;
		}

		.header-avatar {
			width: 56rpx;
			height: 56rpx;
			border-radius: 50%;
			margin-right: 16rpx;
			background-color: white;
			padding: 4rpx;
		}

		.header-title {
			font-size: 28rpx;
			font-weight: 500;
		}

		.close-btn {
			width: 52rpx;
			height: 52rpx;
			padding: 0;
			border-radius: 50%;
			margin-left: 360rpx;
			display: flex;
			justify-content: center;
			align-items: center;
		}

	}

	/* 聊天历史区域 */
	.chat-history {
		flex: 1;
		padding: 20rpx;
		overflow-y: auto;
		background-color: #f7f9fc;
		box-sizing: border-box;
	}

	/* 消息行 */
	.message-row {
		display: flex;
		align-items: flex-start;
		margin-bottom: 30rpx;
		width: 100%;
		box-sizing: border-box;
		padding: 0 10rpx;
	}

	/* AI消息行 */
	.ai-row {
		justify-content: flex-start;
	}

	/* 用户消息行 */
	.user-row {
		justify-content: flex-end;
	}

	/* 头像样式 */
	.avatar {
		width: 64rpx;
		height: 64rpx;
		border-radius: 50%;
		flex-shrink: 0;
		margin-top: 5rpx;
	}

	.ai-avatar {
		margin-right: 16rpx;
	}

	.user-avatar {
		margin-left: 16rpx;
	}

	/* 消息气泡 */
	.message-bubble {
		max-width: 70%;
		border-radius: 20rpx;
		padding: 20rpx 24rpx;
		position: relative;
		word-break: break-word;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
		box-sizing: border-box;
	}

	.ai-bubble {
		background-color: white;
		border: 1rpx solid #f0f0f0;
		margin-right: auto;
	}

	.user-bubble {
		background: linear-gradient(135deg, #1e88e5, #42a5f5);
		color: white;
		margin-left: auto;
	}

	/* 气泡内容 */
	.message-content {
		font-size: 28rpx;
		line-height: 1.6;
		margin-bottom: 8rpx;
	}

	/* 时间显示 */
	.message-time {
		font-size: 20rpx;
		text-align: right;
		opacity: 0.7;
	}

	/* 空白占位 */
	.empty-space {
		width: 64rpx;
		flex-shrink: 0;
	}

	/* 输入区域 */
	.input-area {
		padding: 20rpx;
		background-color: white;
		border-top: 1rpx solid #f0f0f0;
	}

	.input-bar {
		display: flex;
		align-items: center;
		background-color: #f7f8fa;
		border-radius: 40rpx;
		padding: 8rpx 16rpx;
	}

	.upload-btn {
		width: 68rpx;
		height: 68rpx;
		padding: 0;
		background-color: transparent;
		border: none;
	}

	.upload-icon {
		width: 36rpx;
		height: 36rpx;
		opacity: 0.7;
	}

	.chat-input {
		flex: 1;
		height: 68rpx;
		padding: 0 16rpx;
		background-color: transparent;
		font-size: 28rpx;
		color: #333;
		border: none;
	}

	.send-btn {
		width: 100rpx;
		height: 68rpx;
		margin-left: 10rpx;
		background: linear-gradient(135deg, #1e88e5, #1565c0);
		color: white;
		border-radius: 34rpx;
		font-size: 28rpx;
		padding: 0;
		border: none;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.send-btn.disabled {
		background-color: #cccccc;
		opacity: 0.7;
	}

	.loading-indicator {
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.loading-dot {
		width: 10rpx;
		height: 10rpx;
		background-color: white;
		border-radius: 50%;
		margin: 0 3rpx;
		animation: loading 1.4s infinite ease-in-out both;
	}

	.loading-dot:nth-child(1) {
		animation-delay: -0.32s;
	}

	.loading-dot:nth-child(2) {
		animation-delay: -0.16s;
	}

	.status-area {
		margin-top: 16rpx;
		min-height: 40rpx;
		text-align: center;
	}

	.loading-hint {
		color: #999;
		font-size: 24rpx;
	}

	.error-message {
		color: #ff4d4f;
		font-size: 24rpx;
	}

	/* 动画 */
	@keyframes loading {

		0%,
		80%,
		100% {
			transform: scale(0.4);
		}

		40% {
			transform: scale(1);
		}
	}
</style>